/**
 * 
 */
package it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.storemenu;

import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.ImageCache;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.OverallGUILayoutFactory;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.components.ThinScrollBar;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.GameManagerMenu;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.storemenu.charshop.CharStoreCointainer;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.gamemanagermenu.storemenu.itemshop.ItemStoreContainer;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.CharBoughtEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.CharSoldEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.CharacterClickEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEvent;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEventListener;
import it.unical.canonaco.rende.igpe.game.cbv.guilayer.guievents.GraphicEventManager;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.GameManager;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.filehandlers.IniLoader;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.Character;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.component.pawn.stats.StatsFactory;
import it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.managers.StoreManager;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * @author Massimo Canonaco
 *
 */
public class StorePanel extends JPanel implements GraphicEventListener{

	private static final long serialVersionUID = -3917921360344755089L;
	private static String CHARACTERS = "PERSONAGGI";
	private static String ITEMS = "OGGETTI";
	private static String BACK = "INDIETRO";
	static public final String STORE_PANEL_NAME = "storePanel";
	static private final String SETTINGS_FILE = "cbvapps"+File.separator+"uiresource"+File.separator+"storeschema.ini";
	private HashMap<String,String> settings;
	private OverallGUILayoutFactory guiCreator;
	private GraphicEventManager gem = GraphicEventManager.getInstance();
	private StoreManager storeManager;
	private ImageCache imgCache = new ImageCache();
	Image background;
	private ItemStoreContainer itemStore;
	private CharStoreCointainer charStore;
	private JButton switchButton;
	public DefaultListModel charListModel = new DefaultListModel();
	private JList charList;
	private ImageIcon charactersIcon;
	private ImageIcon itemsIcon;

	
	
	public final static String BACKGROUND_IMAGE = "store.background.image",
						COLOR_NEUTRAL = "store.text.color.neutral",
						COLOR_NEGATIVE = "store.text.color.negative",
						COLOR_POSITIVE = "store.text.color.positive",
						STATS_NAME_WIDTH = "store.stats.name.width",
						STATS_NAME_TEXT_SIZE = "store.stats.name.text.size",
						STATS_JLABEL_HEIGHT = "store.stats.jlabel.height",
						STATS_VALUE_WIDTH = "store.stats.value.width",
						STATS_VALUE_TEXT_SIZE =  "store.stats.value.text.size",
						ITEM_IMAGE_PATH = "store.item.image.path",
						ITEM_IMAGE_EXTENSION = "store.item.image.extension",
						AVATAR_IMAGE_PATH = "store.avatar.image.path",
						AVATAR_IMAGE_EXTENSION = "store.avatar.image.extension",
						AVATAR_IMAGE_HEIGHT = "store.avatar.image.height",
						BAG_IMAGE = "store.inventory.bag.image",
						COIN_IMAGE = "store.coin.image",
						COIN_SCALE = "store.coin.scale",
						SPACE = " ",
						EMPTY = "",
						PLUS = "+",
						HASH = "#",
						INSET_TOP = "store.inset.top",
						INSET_RIGHT = "store.inset.right",
						INSET_BOTTOM = "store.inset.bottom",
						INSET_LEFT = "store.inset.left",
						STATS_ICON_PATH = "store.stats.icon.path",
						STATS_ICON_EXTENSION = "store.stats.icon.extension";
	
	public StorePanel(final GameManagerMenu gameMangMenu) {
		
		
		IniLoader iniLoader = new IniLoader(new HashMap<String, String>());
		try {
			iniLoader.load(SETTINGS_FILE);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		GameManager gameManager = gameMangMenu.getMainFrame().getGameManager();
		storeManager = new StoreManager(gameManager.getClientPlayer());
		this.settings = (HashMap<String, String>) iniLoader.getContents();
		this.guiCreator = OverallGUILayoutFactory.getInstance();
		
		this.itemStore = new ItemStoreContainer(gem,storeManager,settings, imgCache);
		this.charStore = new CharStoreCointainer(gem, storeManager, settings, imgCache, gameManager.getStatsFactory(), charListModel );
		
		GridBagConstraints gbc = new GridBagConstraints();
		this.setLayout(new GridBagLayout());
		
		charactersIcon = new ImageIcon(guiCreator.createImageButton(40, CHARACTERS, 150,50, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE));
		itemsIcon = new ImageIcon(guiCreator.createImageButton(40, ITEMS, 150,50, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE));
		
		switchButton = guiCreator.createButtonUniState(40, CHARACTERS, 150,50, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE);
		background = (BufferedImage) imgCache.getImage(settings.get(BACKGROUND_IMAGE));
		gem.addListener(this, CharBoughtEvent.class);
		gem.addListener(this, CharSoldEvent.class);
		
		final List<Character> characters = storeManager.getPlayer().getCharacters();
		
		for(Character c : characters )
			charListModel.addElement(c.getName());
		
     	charList = new JList(charListModel);
     	charList.setOpaque(false);
		charList.setVisibleRowCount(10);
		charList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		JScrollPane scrollPane = new JScrollPane(charList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
               								JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane.setVerticalScrollBar(new ThinScrollBar(JScrollBar.VERTICAL));		
		scrollPane.setPreferredSize(new Dimension(150,250));
		scrollPane.setBackground(new Color(226,243,253,64));
//		scrollPane.setOpaque(false);
		scrollPane.getViewport().setOpaque(false);
		scrollPane.getViewport().setBorder(null);
		scrollPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.DARK_GRAY.brighter(),2), 
				BorderFactory.createLineBorder(Color.WHITE,1) ));
		
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.anchor = GridBagConstraints.FIRST_LINE_START;
		gbc.insets = new Insets(Integer.parseInt(settings.get(StorePanel.INSET_TOP)),
				Integer.parseInt(settings.get(StorePanel.INSET_LEFT)),Integer.parseInt(settings.get(StorePanel.INSET_BOTTOM)),
				Integer.parseInt(settings.get(StorePanel.INSET_RIGHT)));
		this.add(scrollPane, gbc);
		
		gbc.gridx = 1;
		gbc.gridy = 0;
		gbc.gridheight = 3;
		gbc.anchor = GridBagConstraints.FIRST_LINE_START;
		this.add(itemStore, gbc);
		charStore.setVisible(false);
		this.add(charStore,gbc);
		
		gbc.gridy = 1;
		gbc.gridheight = 1;
		JButton backButton = guiCreator.createButtonUniState(40, BACK, 150,50, OverallGUILayoutFactory.BUTTON_STATE_ACTIVE);
		backButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				gameMangMenu.showGM(false);
			}
		});
		
		gbc.gridx = 0;
		gbc.gridy = 1;
		gbc.gridheight = 1;
		this.add(switchButton,gbc);
		switchButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				if(!itemStore.isVisible()){
					charStore.setVisible(false);
					itemStore.setVisible(true);
				
					switchButton.setIcon(charactersIcon);
					switchButton.setRolloverIcon(charactersIcon);
				} else {
				itemStore.setVisible(false);
				charStore.setVisible(true);
				switchButton.setIcon(itemsIcon);
				switchButton.setRolloverIcon(itemsIcon);
				}
			}
		});
		
		gbc.gridx = 0;
		gbc.gridy = 2;
		this.add(backButton,gbc);
		
		charList.addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				
				//otherwise mouse click would fire this event twice
				if(!e.getValueIsAdjusting()){
				
					storeManager.setCurrentSelectedBag(StoreManager.NONE);
					
//					AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("cbvapps"+File.separator+"sounds"+File.separator+"selectmenu.wav").getAbsoluteFile());
//					Clip clip = AudioSystem.getClip();
//					clip.open(audioInputStream);
//					clip.start();
				
				
				
				JList list = (JList) e.getSource();
				int index = list.getSelectedIndex();
				if(index != -1){
				Character clickedChar = characters.get(index);
				storeManager.setCurrentSelectedChar(clickedChar);
				CharacterClickEvent cce = new CharacterClickEvent(clickedChar, index);
				gem.fireEvent(cce);}
				}
			}
		});
		
		charList.setSelectedIndex(0);
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		super.paintComponent(g);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		float widthRatio = (float) background.getWidth(null) / screenSize.width;
		float heightRatio = (float) background.getHeight(null) / screenSize.height;
	
		if(widthRatio < 1.0 && heightRatio < 1.0){
		 int widthFactor = -1;
         int heightFactor = -1;
         if ((widthRatio > heightRatio) && (widthRatio > 1.0))
             widthFactor = screenSize.width;
         else if ((heightRatio > widthRatio) && (heightRatio > 1.0))
             heightFactor = screenSize.height;
         
         if ((widthFactor > 0) && (heightFactor > 0)) {
             background = background.getScaledInstance(widthFactor, heightFactor, Image.SCALE_SMOOTH);
             imgCache.putImage(BACKGROUND_IMAGE, background);
         }
	}
	g2d.drawImage(background, 0, 0, (int) screenSize.getWidth(), (int)screenSize.getHeight(), null);
	}
	
	@Override
	public void notify(GraphicEvent event) {
		
		Class eventClass = event.getClass();
		
		if( eventClass == CharBoughtEvent.class){
			
			CharBoughtEvent cbe = (CharBoughtEvent) event;
			charListModel.addElement(cbe.getBoughtChar().getName());
		
		} else if( eventClass == CharSoldEvent.class){
			charList.setSelectedIndex(0);
		}
			
		repaint();
		
	}
	
}// end StorePanelclass


